package com.example.interceptor.controller;


import com.example.interceptor.utils.jwt.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private JWTUtils jwtUtils;

    @GetMapping("login")
    public String login(HttpServletRequest req){
        System.out.println("执行了login！");
        // 登录成功，创建会话
        HttpSession session = req.getSession(true);
        session.setAttribute("admin","lisi");
        return "lisi login";
    }

    @GetMapping("loginOK")
    public String loginOK(HttpServletRequest req){
        // 登录成功，创建会话
        HttpSession session = req.getSession(true);
        session.setAttribute("admin","lisi");
        HashMap<String, String> map = new HashMap<>();
        map.put("admin","lisi");
        map.put("shenfen","guanliyuan");
        String token = JWTUtils.getToken(map);
        System.out.println(JWTUtils.decode(token));
        System.out.println(JWTUtils.decode(token).getClaim("admin").asString());
        return "login OK " + token;
    }

    @GetMapping("reg")
    public String reg(){
        return "reg";
    }

    @GetMapping("index")
    public String index(HttpServletRequest req){
        HttpSession session = req.getSession(false);
        Object admin = session.getAttribute("admin");
        System.out.println(admin);
        return "index";
    }

    @GetMapping("logout")
    public void logout(HttpServletRequest req){
        HttpSession session = req.getSession(false);
        if (session != null) {
            session.invalidate(); // 使当前会话无效，从而退出登录
        }

    }
}
